package com.wx.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wx.cache.WxMsgTypeCache;
import com.wx.core.process.WxApi;
import com.wx.core.vo.FansTotal;
import com.wx.entity.SysWxuser;
import com.wx.entity.WxFansUser;
import com.wx.entity.WxUserEventGroupBy;
import com.wx.service.SysWxTokenService;
import com.wx.service.SysWxuserService;
import com.wx.service.WxFansGroupService;
import com.wx.service.WxFansUserService;
import com.wx.service.WxUserEventService;
import com.wx.util.DateTimeUtil;
import com.wx.util.JsonResult;
import com.wx.util.JsonUtil;
import com.wx.util.StringUtils;
import com.wx.vo.WxBehaviorSex;
import com.wx.vo.WxUserEventResult;
import com.zyht.common.AbsManageBaseController;
import com.zyht.common.util.HttpUtils;
 
/**
* @ClassName: WxFansBehaviorController
* @Description: 粉丝行为分析
* @author A18ccms a18ccms_gmail_com
* @date 2015年7月23日 下午12:30:55
*
*/ 
@Controller
@RequestMapping("admin/fansBehavior")
public class WxFansBehaviorController extends AbsManageBaseController{
	@Resource
	private SysWxTokenService sysWxTokenService;
	@Resource
	private WxFansGroupService wxFansGroupService;
	@Resource
	private SysWxuserService sysWxuserService;
	
	@Resource
	private WxFansUserService wxFansUserService;
	
	@Resource
	private WxUserEventService wxUserEventService;
	
	
	@Value("#{propertiesReader[session_wx_key]}")
	private String session_wx_key;
	
	private static final Logger logger = LoggerFactory.getLogger(WxFansBehaviorController.class);
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public  String index() {
		return "/crm/behavior";
	}
	@RequestMapping(value = "/total", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
	public @ResponseBody String total(Model model,HttpServletRequest request, HttpSession session) {
		SysWxuser sysWxuser = getSessionWxUser(request);
		String accessToken = sysWxTokenService.getAccessToken(sysWxuser.getWxid(), sysWxuser.getAppid(), sysWxuser.getAppsecretd());
		if(StringUtils.isEmpty(accessToken)){
			model.addAttribute("msg", "公众丢失授权绑定");
			model.addAttribute("redirect", "admin/sysuser/list");
			return "message";
		}
		// 分组列表
		String requestUrl = WxApi.getRequestUrl(WxApi.FANS_TOTAL,accessToken);
		String  json = "{\"begin_date\": \""+DateTimeUtil.getDateStr(7)+"\", \"end_date\": \""+DateTimeUtil.getDateStr(1)+"\"}}";
		String result = HttpUtils.httpsPost(requestUrl,json);
		JSONObject jsonObject = JSONObject.parseObject(result);
		ArrayList<String> datelist = new ArrayList<String>();
		ArrayList<Integer> numlist = new ArrayList<Integer>();
		if(jsonObject != null ){
			logger.debug("******返回数据*********"+jsonObject.toString());
			@SuppressWarnings("unchecked")
			ArrayList<FansTotal> list = (ArrayList<FansTotal>)JsonUtil.str2list(jsonObject.getJSONArray("list").toString(), FansTotal.class);
			for (FansTotal fansTotal : list) {
				datelist.add(fansTotal.getRef_date());
				numlist.add(Integer.valueOf(fansTotal.getCumulate_user()));
			}
		}
 
		HashMap<String ,List<?>> map = new HashMap<String ,List<?>>();
		map.put("dateStr", datelist);
		map.put("numStr", numlist);
		return JsonUtil.Object2Json(JsonResult.objectJson(map));
	}
	@RequestMapping(value = "/sexCount", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
	public @ResponseBody String sexCount(HttpSession session,HttpServletRequest request) {
		SysWxuser sysWxuser = getSessionWxUser(request);
		List<WxFansUser> list = wxFansUserService.selectByWxid(sysWxuser.getWxid());
		int manCount = 0;
		int womanCount = 0;
		int unknownCount = 0;
		for (WxFansUser wxFansUser : list) {
			if (wxFansUser.getSex() == 1)
				manCount++;
		    else if (wxFansUser.getSex() == 2)
				womanCount++;
			else
				unknownCount++;
		}
	    
		List<WxBehaviorSex> relist = new ArrayList<WxBehaviorSex>();
		relist.add(new WxBehaviorSex("男," + manCount,manCount));
		relist.add(new WxBehaviorSex("女," + womanCount,womanCount));
		relist.add(new WxBehaviorSex("未知," + unknownCount,unknownCount));
		 
		return JsonUtil.Object2Json(JsonResult.objectJson(relist));
	}
	@RequestMapping(value = "/fan", method = RequestMethod.GET)
	public  String fan(@RequestParam(value = "openid", required = false) final String openid,HttpServletRequest request) {
		 
		List<WxUserEventGroupBy> list = wxUserEventService.selectGroupByDate(openid);
 
		List<WxUserEventResult> relist = new ArrayList<WxUserEventResult>();
		for (WxUserEventGroupBy weg : list) {
			WxUserEventResult wxResult =new WxUserEventResult();
			BeanUtils.copyProperties(weg, wxResult);
			String wxMsgType = WxMsgTypeCache.msgTypeMap.get(weg.getMsgtype());
			if(StringUtils.isEmpty(wxMsgType)){
				wxMsgType = "其他";
			}
			wxResult.setMsgtypeStr(wxMsgType);
			relist.add(wxResult);
		}
		request.setAttribute("relist", relist);
		return "/crm/fan_behavior";
	}
	
	/**
	 * 粉丝总行为统计
	 * @author: InkYi
	 * 修改时间：2016年4月13日 - 下午4:20:10<br/>
	 * 功能说明：<br/>
	 * @return
	 */
	@RequestMapping(value = "/fanCount", method = RequestMethod.GET)
	public @ResponseBody String fanCount(HttpServletRequest requeset) {
		List<WxUserEventResult> events = wxUserEventService.selectFanCountByMonth(getWxId(requeset), 2);
		List<String> xAxis = new ArrayList<>(events.size());
		for (WxUserEventResult wuer : events) {
			String wxMsgType = WxMsgTypeCache.msgTypeMap.get(wuer.getMsgtype());
			if(StringUtils.isEmpty(wxMsgType)){
				wxMsgType = "其他";
			}
			wuer.setMsgtypeStr(wxMsgType);
			xAxis.add(wxMsgType);
		}
		return JsonUtil.Object2Json(events);
	}

	@RequestMapping(value = "/fansEventCount", method = RequestMethod.GET, produces="application/json;charset=utf-8")
	public @ResponseBody String fansCountStatics(HttpServletRequest requeset){
		List<WxUserEventResult> events = wxUserEventService.selectFanCountByMonth(getWxId(requeset), 2);
		int len = events.size();
		List<String> xAxis = new ArrayList<>(len);
		List<Integer> dataList = new ArrayList<>(len);
		for (WxUserEventResult wuer : events) {
			String wxMsgType = WxMsgTypeCache.msgTypeMap.get(wuer.getMsgtype());
			if(StringUtils.isEmpty(wxMsgType)){
				wxMsgType = "其它";
			}
			xAxis.add(wxMsgType);
			dataList.add(wuer.getCount());
		}
		Map<String, Object> result = new HashMap<>();
		result.put("xAxis",xAxis);
		result.put("data",dataList);
		return JSON.toJSONString(result);
	}	
}
